/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.renderer;

import com.jb.faces.component.UIComponent;
import com.jb.web.bean.Grid;
import com.jb.web.bean.HtmlItem;
import com.jb.web.bean.ListBean;
import com.jb.web.bean.TableCell;
import com.jb.web.bean.TableRow;
import com.jb.web.context.WebContext;

import java.util.Iterator;


public class ListBeanRenderer extends GridRenderer {
    public StringBuffer render(WebContext pCtx, UIComponent itemToRender) {
        if (!isEditable(pCtx, (HtmlItem) itemToRender)) {
            return super.render(pCtx, itemToRender);
        } else {
            return renderDesignTime(pCtx, itemToRender);
        }
    }
    
    protected StringBuffer renderRow(WebContext ctx, TableRow row, int rowNo, boolean selected) {
        StringBuffer html = new StringBuffer();
        String rid = row.getClientId(ctx);
        ListBean lb= (ListBean)row.getParent();
        
        html.append("<div ").append(getEditScript(ctx,row));
        String onSelectRow = lb.getOnSelectRow();
        if(onSelectRow!=null&&onSelectRow.startsWith("client:")) {
            html.append(" onSelectRow=\""+onSelectRow.substring(7)+"\"");
        }

         if(!selected)
            html.append(" class=\"jb_row ");
         else
             html.append(" class=\"jb_row_selected ");

         html.append(id)
                .append("_row\" style=\"width:")
                .append(innerTableWidth)
                .append("px;\" ");
        StringBuffer sb=new StringBuffer(rid+"','"+id);
        html.append("onmouseover=\"JBTable.onRowMouseOver(event,'")
                .append(sb)
                .append("');\" onclick=\"JBTable.onRowSelect(event,'")
                .append(sb)
                .append("');\" onmousemove=\"JBTable.onRowMouseMove(event,'")
                .append(sb)
                .append("');\" onmouseout=\"JBTable.onRowMouseOut(event,'")
                .append(sb)
                .append("');\"> <table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"jb_row_table ")
                .append(id)
                .append("_row\" style=\"width: ")
                .append(innerTableWidth)
                .append("px;\"><tbody> <tr >");
        
        Iterator iter = row.getChildrenSorted(null).iterator();
        int i=0;
        String firstCol="_first";
        while(iter.hasNext()) {
            TableCell tc = (TableCell)iter.next();
            String cid=id+"_"+rowNo+"_"+i;
            tc.setClientId(cid);
            html.append("<td style=\"width: ")
                .append( columnWidth[i])
                .append("px;\"" );
            html.append(addTagProperty("class", "jb_cell", null))
                .append(getEditScript(ctx,tc));
            html.append("><div id=\"")
                .append(tc.getClientId())
                .append("_c\" class=\"jb_cell_inner")
                .append((i==0?firstCol:""))
                .append(" ")
                .append(id)
                .append("_")
                .append(i)
                .append(" ")
                .append((columnStyleClass[i]==null?columnStyleClass[i]:""))
                .append(" \" style=\"width: ")
                .append(columnWidth[i])
                .append("px;\">");
            html.append(renderCell(ctx, tc));
            html.append("</div></td>");
            i++;
        }
        html.append("</tr></tbody></table></div>");
        return html;
    }

    protected StringBuffer renderRows(WebContext ctx, UIComponent itemToRender) {
        ListBean hItem = (ListBean) itemToRender;
      
        StringBuffer html = new StringBuffer();

        int size = hItem.getSize();
        int cols = hItem.getColumns();

        int iStartAt = hItem.getStart();
        int iEndAt = iStartAt + hItem.getBlockSize();

        if (iEndAt > size) {
            iEndAt = size;
        }

        TableRow row1 = hItem.getRow(0);
        TableRow row2 = hItem.getRow(1);

        TableRow row = row1;
        int oldSeq = hItem.getSequence();
        int rowno = 0;
        int i = 0;

        while (i < (iEndAt - iStartAt)) {
            row = row1;

            if (((rowno % 2) == 1) && (row2 != null)) {
                row = row2;
            }

            row.setClientId("r" + hItem.getId() + "_" + i);

            TableCell cell = row.getCellAt(0);
            int width = 100 / cols;
            cell.setWidth("" + width + "%");
            if (i < (iEndAt - iStartAt)) {
                
                hItem.setCurrentRow(hItem.get(iStartAt + i));
                hItem.setSequence(i);
                html.append(renderRow(ctx, row, i, i==hItem.getSelected()));
                i++;
            }
            hItem.setCurrentRow(null);
            rowno++;
        }

        hItem.setSequence(oldSeq); //reset sequence here

        return html;
    }
  
    private StringBuffer renderDesignTime(WebContext pCtx, UIComponent itemToRender) {
        StringBuffer html = new StringBuffer();
        Grid hItem = (Grid) itemToRender;

        html.append("<table ").append(getEditScript(pCtx, hItem)).append(">");

        if (hItem.isShowHeader() && (hItem.getHeader(pCtx) != null)) {
            html.append(hItem.getHeader(pCtx).render(pCtx));
        }

        for (int i = 0; i < hItem.getRows(); i++) {
            try {
                TableRow row = hItem.getRow(i);
                html.append(row.render(pCtx));
            } catch (Exception e) {
                pCtx.addErrorMessage(hItem, e.getMessage());
            }
        }


        if (hItem.getRows() == 0) {
            html.append("<tr><td>At least one row for a list</td></tr> ");
        }

        html.append("</table>");

        return html;
    }

}